package network;

import java.util.*;

public class Neighbours {

	public HashMap<String, Long> neighboursTable;

	static long timeout = 4000;

	public Neighbours() {
		neighboursTable = new HashMap<String, Long>();
	}

	public synchronized void updateTable(String neighbour) {
		boolean update = false;
		if (!neighboursTable.containsKey(neighbour)) {
			System.err.println("Added neighbour " + neighbour);
			if (!NetworkLayer.bellman.distances.containsKey(NetworkLayer.myID)) {
				NetworkLayer.bellman.distances.put(NetworkLayer.myID,
						new DistanceCouple());
			}
			NetworkLayer.bellman.distances.get(NetworkLayer.myID)
					.alterDistances(neighbour, 1);
			update = true;
		}
		neighboursTable.put(neighbour, System.currentTimeMillis());
		if (update) {
			NetworkLayer.bellman.updateVia();
		}
	}

	public synchronized void checkTimeouts() {
		LinkedList<String> toDelete = new LinkedList<String>();
		for (String s : neighboursTable.keySet()) {
			if (System.currentTimeMillis() - neighboursTable.get(s) > timeout) {
				toDelete.add(s);
			}
		}
		boolean update = false;
		for (String s : toDelete) {
			System.err.println("Neighbour " + s + " removed due to inactivity");
			neighboursTable.remove(s);
			update = true;
		}
		if (update) {
			NetworkLayer.bellman.updateVia();
		}
	}
}
